package com.qishon.pc.domain.service;

import com.qishon.pc.domain.repository.impl.PreViewRepositoryImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * Created by yuquan.hu on 2016/12/23.
 */
@Slf4j
@Service
public class PreUploadService {
    @Value("${run.path}")
    private String filePath;
    private String dirfilename;
    @Autowired
    PreViewRepositoryImpl preViewRepositoryImpl;
    @ResponseBody
    public String Message(@RequestParam(value = "filename", required = false) String filename, @RequestParam(value = "file", required = false) MultipartFile file, @RequestParam(value = "file1", required = false) MultipartFile file1, @RequestParam(value = "file2", required = false) MultipartFile file2)
            throws Exception {
        // 创建目录
        dirfilename = filename;
        String re;
//        File dir = new File(filePath+"\\"+"01.Model"+"\\");
//        if (!dir.exists()) {
//            dir.mkdir();
//        }
        File tempdir = new File(filePath+"\\" + "01.Model" + "\\" + dirfilename + "tempfile\\");
        if(!tempdir.exists()){
            tempdir.mkdirs();
        }
        String filepath = filePath+"\\"+"01.Model"+"\\" + filename + "\\";
        File picdir = new File(filepath);
        if (picdir.exists()) {
            return "是否覆盖原有文件夹";
        }
        else {
            re = saveFileToServer(filename,file,file1,file2);
        }
        return re;
    }
    @ResponseBody
    public String saveFileToServer(@RequestParam(value = "filename", required = false) String filename, @RequestParam(value = "file", required = false) MultipartFile file, @RequestParam(value = "file1", required = false) MultipartFile file1, @RequestParam(value = "file2", required = false) MultipartFile file2)
            throws Exception {
        // 创建目录
        String filepath = filePath+"\\"+"01.Model"+"\\" + filename + "\\";
        File picdir = new File(filepath);
        picdir.mkdir();
        int bytesum;
        int byteread;

        // 读取文件流并保持在指定路径
            InputStream inputStream1 = file1.getInputStream();
            //file.getOriginalFilename()
            OutputStream outputStream1 = new FileOutputStream(filepath + filename + "_01.csv");

            byte[] buffer1 = file1.getBytes();
            bytesum = 0;
            byteread = 0;
            while ((byteread = inputStream1.read(buffer1)) != -1) {
                bytesum += byteread;
                outputStream1.write(buffer1, 0, byteread);
                outputStream1.flush();
            }
            outputStream1.close();
            inputStream1.close();

        // 读取文件流并保持在指定路径
            InputStream inputStream2 = file2.getInputStream();
            //file.getOriginalFilename()
            OutputStream outputStream2 = new FileOutputStream(filepath + filename + "_02.csv");

            byte[] buffer2 = file2.getBytes();
            bytesum = 0;
            byteread = 0;
            while ((byteread = inputStream2.read(buffer2)) != -1) {
                bytesum += byteread;
                outputStream2.write(buffer2, 0, byteread);
                outputStream2.flush();
            }
            outputStream2.close();
            inputStream2.close();
        return "文件上传成功";
    }
    public void unZip(String path) throws Exception{
        File inputFile = new File(path);
        String basePth;
        String division[] = path.split("\\\\");
        basePth = division[0];
        for(int i = 1; i < division.length-1; i++){
            basePth += "\\";
            basePth += division[i];
        }
 //       System.out.println(basePth);
        getZip(inputFile,basePth);
    }
    private void getZip( File f, String base) throws Exception {
        ZipInputStream inputStream=new ZipInputStream( new FileInputStream(f));
        BufferedInputStream Bin=new BufferedInputStream(inputStream);
        File Fout=null;
        File Dir = null;
        ZipEntry entry;
        try {
            while((entry = inputStream.getNextEntry())!=null){
                if (entry.isDirectory()) {
                    Dir = new File(base,entry.getName());
                    if(!Dir.exists()){
                        (new File(Dir.getPath())).mkdirs();
                        System.out.println(Dir);
                    }
                }
                else{
                    Fout=new File(base,entry.getName());
                    if(!Fout.exists()){
                        (new File(Fout.getParent())).mkdirs();
                    }
                    FileOutputStream out=new FileOutputStream(Fout);
                    BufferedOutputStream Bout=new BufferedOutputStream(out);
                    int b;
                    while((b=Bin.read())!=-1){
                        Bout.write(b);
                    }
                    Bout.close();
                    out.close();
                    log.info(Fout+"解压成功");
                }
            }
            Bin.close();
            inputStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 获取已上传的文件大小
     * @param request
     * @param response
     */
    public void getChunkedFileSize(HttpServletRequest request, HttpServletResponse response){
        //存储文件的路径，根据自己实际确定
        String currentFilePath = filePath + "\\" + "01.Model" + "\\" + dirfilename + "tempfile\\";
        PrintWriter print = null;
        try {
            request.setCharacterEncoding("utf-8");
            print = response.getWriter();
            String fileName = new String(request.getParameter("fileName").getBytes("ISO-8859-1"),"UTF-8");
            String lastModifyTime = request.getParameter("lastModifyTime");
            File file = new File(currentFilePath+fileName+"."+lastModifyTime);
            if(file.exists()){
                print.print(file.length());
            }else{
                print.print(-1);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     *
     * 断点文件上传 1.先判断断点文件是否存在 2.存在直接流上传 3.不存在直接新创建一个文件 4.上传完成以后设置文件名称
     *
     */
    public void appendUpload2Server(HttpServletRequest request,HttpServletResponse response) {
        PrintWriter print = null;
        try {
            request.setCharacterEncoding("utf-8");
            print = response.getWriter();
            String fileSize = request.getParameter("fileSize");
            long totalSize = Long.parseLong(fileSize);
            RandomAccessFile randomAccessfile = null;
            long currentFileLength = 0;// 记录当前文件大小，用于判断文件是否上传完成
            String currentFilePath = filePath + "\\" + "01.Model" + "\\" + dirfilename + "tempfile\\";// 记录临时文件的绝对路径
            String newfilepath = filePath + "\\" + "01.Model" + "\\" + dirfilename + "\\" + dirfilename + ".zip"; // 记录当前文件的绝对路径
            String fileName = new String(request.getParameter("fileName").getBytes("ISO-8859-1"),"UTF-8");
            String lastModifyTime = request.getParameter("lastModifyTime");
            File file = new File(currentFilePath+fileName+"."+lastModifyTime);
            // 存在文件
            if(file.exists()){
                randomAccessfile = new RandomAccessFile(file, "rw");
            }
            else {
                // 不存在文件，根据文件标识创建文件
                randomAccessfile = new RandomAccessFile(currentFilePath+fileName+"."+lastModifyTime, "rw");
            }
            // 开始文件传输
            InputStream in = request.getInputStream();
            randomAccessfile.seek(randomAccessfile.length());
            byte b[] = new byte[1024];
            int n;
            while ((n = in.read(b)) != -1) {
                randomAccessfile.write(b, 0, n);
            }

            currentFileLength = randomAccessfile.length();

            // 关闭文件
            closeRandomAccessFile(randomAccessfile);
            randomAccessfile = null;
            // 整个文件上传完成,修改文件后缀
            if (currentFileLength == totalSize) {
                File oldFile = new File(currentFilePath + fileName+"."+lastModifyTime);
                File newFile = new File(newfilepath);
                if(!oldFile.exists()){
                    return;//重命名文件不存在
                }
                if(newFile.exists()){// 如果存在形如test.txt的文件，则新的文件存储为test+当前时间戳.txt, 没处理不带扩展名的文件
//                    String newName = fileName.substring(0,fileName.lastIndexOf("."))
//                            +System.currentTimeMillis()+"."
//                            +fileName.substring(fileName.lastIndexOf(".")+1);
//                    newFile = new File(currentFilePath+newName);
                    newFile.delete();
                }
                if(oldFile.renameTo(newFile)){
                    File olddir = new File(currentFilePath);
                    if(olddir.exists()){
                        olddir.delete();
                    }
                    unZip(newfilepath);
                }

            }
            print.print(currentFileLength);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 关闭随机访问文件
     *
     * @param rfile
     */
    public static void closeRandomAccessFile(RandomAccessFile rfile) {
        if (null != rfile) {
            try {
                rfile.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
